package com.seeyon.apps.kk.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.organization.bo.V3xOrgRole;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.annotation.NeedlessCheckLogin;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.kk.utils.CoreUtils;
import com.seeyon.kk.utils.ValueUtils;

@NeedlessCheckLogin
public class KKSSOController extends KkBaseController {

	/**
	 * 单点认证
	 * 
	 * @param request
	 * @param response
	 */
	public void ssoHb(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 如果档案系统 共用接口 传 type 验证
			// String type = request.getParameter("type");
			String backUrl = ValueUtils.getConfig().getString("shkk.ssoTOMeetingUrl");
			User user = AppContext.getCurrentUser();
			if (null == user) {
				response.sendRedirect("/seeyon/main.do");
				return;
			}
			String loginName = user.getLoginName();
			if (StringUtils.isNotEmpty(loginName)) {
				Long id = UUIDLong.longUUID();
				Map<String, Object> map = new HashMap<>();
				map.put("id", id);
				map.put("loginName", loginName);
				map.put("ticket", id);
				map.put("crate_date", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("addticket_insert", map);
				response.sendRedirect(backUrl + id);
			}
		} catch (Exception e) {
			WorkflowEventResult er = new WorkflowEventResult();
			er.setAlertMessage("单点认证错误：" + e.getMessage());
		}
	}

	/**
	 * 验证ticket
	 * 
	 * @param request
	 * @param response
	 */
	public void ssoTicket(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String ticket = request.getParameter("ticket");
			Map<String, String> map = Maps.newHashMap();
			map.put("ticket", ticket);
			List<Map<String, Object>> list = this.ibatisQueryDao.getSqlMapClientTemplate()
					.queryForList("queryByticket_select", map);
			String msg = "";
			if (!list.isEmpty()) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				long from = simpleDateFormat.parse(MapUtils.getString(list.get(0), "field0003")).getTime();
				long to = simpleDateFormat.parse(simpleDateFormat.format(new Date())).getTime();
				int minutes = (int) ((to - from) / (1000 * 60));
				if (minutes > 1) {
					msg = "{\"code\":1,\"msg\":\"请求超时！\",\"loginName\":\"\"}";
					response.getWriter().print(msg);
				} else {
					this.ibatisQueryDao.getSqlMapClientTemplate().delete("removeByticket_delete", map);
					msg = "{\"code\":0,\"msg\":\"登陆成功！\",\"loginName\":\""
							+ MapUtils.getString(list.get(0), "field0001") + "\"}";
					response.getWriter().print(msg);
				}
			} else {
				msg = "{\"code\":1,\"msg\":\"ticket 不存在！\",\"loginName\":\"\"}";
				response.getWriter().print(msg);
			}
		} catch (Exception e) {
			WorkflowEventResult er = new WorkflowEventResult();
			er.setAlertMessage("ticket 验证错误：" + e.getMessage());
		}

	}

	/**
	 * 单点登录至NC系统
	 * 
	 * @param request
	 * @param response
	 */
	public void ssoTONC(HttpServletRequest request, HttpServletResponse response) {
		String seeyonUrl = request.getScheme() + "://" + request.getServerName();
		String ssoRegServlet = ValueUtils.getConfig().getString("shkk.ssoRegServlet");
		String ssoTONCUrl = ValueUtils.getConfig().getString("shkk.ssoTONCUrl");
		User user = AppContext.getCurrentUser();
		try {
			if (null == user) {
				response.sendRedirect("/seeyon/main.do");
				return;
			}
			String ssoKey = CoreUtils
					.doGet(ssoRegServlet, "userCode=" + user.getLoginName() + "&busiCenter=01", "UTF-8", true)
					.replace("\r\n", "");
			if (ssoKey != null && !ssoKey.equals("")) {
				// +"&uiloader=nc.uap.lfw.applet.PortalUILoader" 调用客户端
				response.sendRedirect(ssoTONCUrl + ssoKey);
			} else {
				WorkflowEventResult er = new WorkflowEventResult();
				er.setAlertMessage("获取NC认证错误！");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("登录NC认证重定向错误：" + e.getMessage());
		}
	}

	/**
	 * 返回js页面 通过js实现登陆
	 * 
	 * @param request
	 * @param response
	 */
	public ModelAndView ssoTOPLM(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView(ROOT_PATH + "/serjs/ssoPLMJS");
		User user = AppContext.getCurrentUser();
		try {
			if (null == user) {
				response.sendRedirect("/seeyon/main.do");
				return mav;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mav.addObject("currentUser", user.getLoginName());
		return mav;
	}

	/**
	 * 单点登录至BQ系统
	 * 
	 * @param request
	 * @param response
	 */
	public void ssoTOBQ(HttpServletRequest request, HttpServletResponse response) {
		String ssoRegServlet = ValueUtils.getConfig().getString("shkk.ssoRegServletBQ");
		String ssoTONCUrl = ValueUtils.getConfig().getString("shkk.ssoTOBQUrl");
		User user = AppContext.getCurrentUser();
		try {
			if (null == user) {
				response.sendRedirect("/seeyon/main.do");
				return;
			}
			// +"&busiCenter=nc65"
			String ssoKey = CoreUtils.doGet(ssoRegServlet, "userCode=" + user.getLoginName(), "UTF-8", true)
					.replace("\r\n", "");
			if (ssoKey != null && !ssoKey.equals("")) {
				response.sendRedirect(ssoTONCUrl + ssoKey);
			} else {
				WorkflowEventResult er = new WorkflowEventResult();
				er.setAlertMessage("获取BQ认证错误！");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("登录BQ认证重定向错误：" + e.getMessage());
		}
	}

	/**
	 * 单点至Email
	 * 
	 * @param request
	 * @param response
	 */
	public void ssoTOEmail(HttpServletRequest request, HttpServletResponse response) {
		String ssoEmailKey = ValueUtils.getConfig().getString("shkk.ssoEmailKey");
		String ssoTOEmailUrl = ValueUtils.getConfig().getString("shkk.ssoTOEmailUrl");
		User user = AppContext.getCurrentUser();
		String msg = "";
		try {
			if (null == user) {
				response.sendRedirect("/seeyon/main.do");
				return;
			}
			String ssoKey = CoreUtils.doGet(ssoEmailKey,
					"passkey=" + CoreUtils.emailMd5() + "&key=" + user.getLoginName() + "@mail.5715.cn", "UTF-8", true)
					.replace("\r\n", "");
			if (ssoKey != null && !ssoKey.equals("")) {
				Map<String, Object> result = JSON.parseObject(ssoKey);
				if (MapUtils.getInteger(result, "errcode") == 0) {
					response.sendRedirect(ssoTOEmailUrl + MapUtils.getString(result, "result"));
				} else {
					msg = "{\"code\":" + MapUtils.getInteger(result, "errcode")
							+ ",\"msg\":\"登录失败！请检查邮箱系统账号是否存在！\",\"loginName\":\"" + user.getLoginName() + "\"}";
					response.getWriter().print(msg);
				}

			} else {
				msg = "{\"code\":-1,\"msg\":\"请求错误！\",\"loginName\":\"\"}";
				response.getWriter().print(msg);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("登录Email 认证重定向错误：" + e.getMessage());
		}
	}
}
